import Foundation
import SwiftUI
import CoreMotion

// 共享的耳机运动数据记录器
final class MotionRecorder: ObservableObject {
    private let headphoneManager = CMHeadphoneMotionManager()
    
    // 公共状态
    @Published var isListening: Bool = false
    @Published var statusMessage: String = "点击开始监听"
    @Published var lastReadingText: String = "等待数据..."
    @Published var lastUpdateTime: String = ""
    @Published var dataPoints: [GyroDataPoint] = []
    
    // 可调参数
    var maxDataPoints: Int = 100
    
    // 只读的底层能力状态
    var isDeviceMotionAvailable: Bool { headphoneManager.isDeviceMotionAvailable }
    var isDeviceMotionActive: Bool { headphoneManager.isDeviceMotionActive }
    
    // 开始采集
    func start() {
        guard isDeviceMotionAvailable else {
            statusMessage = "❌ 当前设备不支持耳机运动数据"
            print("当前设备不支持耳机运动数据")
            return
        }
        statusMessage = "🔄 正在启动监听..."
        isListening = true
        
        headphoneManager.startDeviceMotionUpdates(to: .main) { [weak self] motion, error in
            guard let self = self else { return }
            if let error = error {
                self.statusMessage = "❌ 获取运动数据出错: \(error.localizedDescription)"
                self.isListening = false
                print("获取运动数据出错: \(error.localizedDescription)")
                print("错误详情: \(error)")
                return
            }
            
            // 检查是否真的开始接收数据
            if !self.isDeviceMotionActive {
                self.statusMessage = "❌ 无法启动耳机运动监听，请确保AirPods已连接并佩戴"
                self.isListening = false
                print("无法启动耳机运动监听，请确保AirPods已连接并佩戴")
                return
            }
            
            if let motion = motion {
                let rotationRate = motion.rotationRate
                let attitude = motion.attitude
                let currentTime = Date()
                
                // 新数据点
                let newDataPoint = GyroDataPoint(timestamp: currentTime, rotationRate: rotationRate)
                self.dataPoints.append(newDataPoint)
                if self.dataPoints.count > self.maxDataPoints {
                    self.dataPoints.removeFirst()
                }
                
                // 更新可读文本
                self.statusMessage = "✅ 正在监听中..."
                self.lastReadingText = """
                陀螺仪 (rad/s):
                X: \(String(format: "%.4f", rotationRate.x))
                Y: \(String(format: "%.4f", rotationRate.y))
                Z: \(String(format: "%.4f", rotationRate.z))
                
                姿态 (quaternion):
                Pitch: \(String(format: "%.2f", attitude.pitch * 180 / .pi))°
                Roll: \(String(format: "%.2f", attitude.roll * 180 / .pi))°
                Yaw: \(String(format: "%.2f", attitude.yaw * 180 / .pi))°
                
                数据点: \(self.dataPoints.count)
                """
                let formatter = DateFormatter()
                formatter.timeStyle = .medium
                self.lastUpdateTime = formatter.string(from: currentTime)
                
                // 控制台输出
                print("陀螺仪数据 - x: \(rotationRate.x), y: \(rotationRate.y), z: \(rotationRate.z)")
            }
        }
    }
    
    // 停止采集
    func stop() {
        headphoneManager.stopDeviceMotionUpdates()
        isListening = false
        statusMessage = "⏹️ 已停止监听"
        lastReadingText = "等待数据..."
        lastUpdateTime = ""
        print("已停止监听耳机运动数据")
    }
}
